package com.shijiwei.lifthelper.ui;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.PoiOverlay;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.shijiwei.lifthelper.R;

public class MapActivity extends Activity {
    // UI
    private MapView mMapView;
    private Button btn_search;
    private TextView tv_city;
    private EditText et_keyword;

    // 工具类
    private BaiduMap mBaiduMap;
    private PoiSearch poiSearch;

    // 定位相关
    private LocationClient mLocationClient;
    private MyLocationListener myLocationListener = new MyLocationListener();

    // 属性
    private boolean isFirst = true;
    private LatLng point;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_map);
        initView();
        mBaiduMap = mMapView.getMap();
        // 开启定位功能
        mBaiduMap.setMyLocationEnabled(true);
        // 初始化定位管理器
        mLocationClient = new LocationClient(getApplicationContext());
        // 设置一个定位选项
        LocationClientOption clientOption = new LocationClientOption();
        clientOption.setOpenGps(true);
        clientOption.setCoorType("bd09ll");
        clientOption.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式 高精度
        clientOption.setScanSpan(2000);// 设置两秒定位一次
        clientOption.setIsNeedAddress(true);// 设置可获得地址
        // 给定位器设置一个定位项
        mLocationClient.setLocOption(clientOption);
        // 设置数据接口回调
        mLocationClient.registerLocationListener(myLocationListener);
        // 开启定位功能
        mLocationClient.start();

        addListner();

    }

    class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public boolean onPoiClick(int i) {
            PoiInfo info = this.getPoiResult().getAllPoi().get(i);
            poiSearch.searchPoiDetail(new PoiDetailSearchOption()
                    .poiUid(info.uid));
            return super.onPoiClick(i);
        }

    }

    private void addListner() {
        poiSearch
                .setOnGetPoiSearchResultListener(new OnGetPoiSearchResultListener() {

                    @Override
                    public void onGetPoiResult(PoiResult arg0) {
                        if (arg0 == null
                                || arg0.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                            Toast.makeText(getApplicationContext(), "没有搜索到结果",
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0.error == SearchResult.ERRORNO.NO_ERROR) {
                            mBaiduMap.clear();// 清楚之前地图上面的所有覆盖物
                            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
                            mBaiduMap.setOnMarkerClickListener(overlay);
                            overlay.setData(arg0);// 设置要添加的覆盖物的数据
                            overlay.addToMap();// 添加覆盖物到地图
                            overlay.zoomToSpan();// 检索结果随地图显示的地点而放大，缩小
                        }
                    }

                    @Override
                    public void onGetPoiDetailResult(PoiDetailResult arg0) {

                        View v = LayoutInflater.from(getApplicationContext())
                                .inflate(R.layout.poi_item, null);
                        ((TextView) v.findViewById(R.id.tv_adress))
                                .setText("地址："
                                        + (arg0.getAddress().equals(null) ? "暂无"
                                        : arg0.getAddress()));
                        ((TextView) v.findViewById(R.id.tv_name)).setText("名称："
                                + (arg0.getName().equals(null) ? "暂无" : arg0
                                .getName()));
                        ((TextView) v.findViewById(R.id.tv_phone))
                                .setText("电话："
                                        + (arg0.getTelephone().equals("") ? "暂无"
                                        : arg0.getTelephone()));
                        ((TextView) v.findViewById(R.id.tv_price))
                                .setText("价格："
                                        + (arg0.getPrice() == 0 ? "暂无" : (arg0
                                        .getPrice() + " 元")));
                        ((TextView) v.findViewById(R.id.tv_shopHours))
                                .setText("营业时间："
                                        + (arg0.getShopHours().equals("") ? "暂无"
                                        : arg0.getShopHours()));
                        InfoWindow window = new InfoWindow(v, arg0
                                .getLocation(), -50);
                        mBaiduMap.showInfoWindow(window);
                    }
                });
    }

    public void initView() {
        // 工具
        mMapView = (MapView) findViewById(R.id.mMapView);
        poiSearch = PoiSearch.newInstance();
        // UI
        btn_search = (Button) findViewById(R.id.btn_search);
        tv_city = (TextView) findViewById(R.id.tv_city);
        et_keyword = (EditText) findViewById(R.id.et_search);
    }

    // 用于接收定位器返回的地址
    class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

            tv_city.setText(location.getCity());
            point = new LatLng(location.getLatitude(), location.getLongitude());
            // 设置定位数据
            mBaiduMap.setMyLocationData(new MyLocationData.Builder()
                    .latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build());
            // 改变地图的状态、设置中心位置
            if (isFirst) { // 如果是第一次进入APP、就想设置地图的中心，不是则不设置
                MapStatus status = new MapStatus.Builder().target(point)
                        .zoom(17).build();
                mBaiduMap.setMapStatus(MapStatusUpdateFactory
                        .newMapStatus(status));
                isFirst = false;
            }
        }

    }

    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_search:
                String keyword = et_keyword.getText().toString();
                poiSearch.searchNearby(new PoiNearbySearchOption().location(point)
                        .keyword(keyword).radius(5000));
                break;

            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        poiSearch.destroy();
        mLocationClient.stop();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mMapView.onDestroy();
        poiSearch.destroy();
        mLocationClient.stop();
        super.onDestroy();
    }
}
